package com.wqiuqiu.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqiuqiu.common.constant.EsConstant;
import com.wqiuqiu.common.to.es.SkuEsModel;
import com.wqiuqiu.gulimallsearch.config.GulimallElasticsearchConfig;
import com.wqiuqiu.gulimallsearch.service.ProductService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String string = JSON.toJSONString(skuEsModel);
            indexRequest.source(string, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        boolean b = bulkResponse.hasFailures();
        return !b;


    }
}
